<template>
  <div :class="[$style.container]" @keyup.enter="onSubmit">
    <div :class="[$style.title]">账号注册</div>
    <el-form :model="form" :rules="rules" ref="fm">
      <el-form-item prop="identifier">
        <el-input v-model.trim="form.identifier" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="credential">
        <el-input v-model.trim="form.credential" type="password" placeholder="建议8-16位，大小写字母、数字或符号3种组合" show-password auto-complete="new-password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%;" :loading="submitting" @click="onSubmit">立即注册</el-button>
      </el-form-item>
      <div class="text-center">
        <el-link :underline="false" style="font-size: 12px;" @click="onGoAccount">账号密码登录</el-link>
      </div>
    </el-form>
    <el-divider></el-divider>
    <action-list></action-list>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Ref, Emit } from 'vue-property-decorator'
import ActionList from '../action-list/index.vue'
import { isAccountBound, bindUsername } from '@/api/account'
import { passwordValidator, phoneValidator } from '@/config/validator'

@Component({
  components: { ActionList }
})
export default class AccountRegistry extends Vue {
  @Prop(String) type!: 'phone' | 'username' | 'registry'

  @Ref() fm!: any

  @Emit('update:type') updateType (type: 'phone' | 'username' | 'registry') {}

  form = {
    identifier: '',
    credential: ''
  }

  submitting = false

  get rules () {
    return {
      identifier: [
        { required: true, message: '请输入账号' }
      ],
      credential: [
        { required: true, message: '请输入密码' },
        { validator: passwordValidator }
      ]
    }
  }

  onSubmit () {
    this.fm.validate((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      isAccountBound(this.form.identifier, 'username').then(data => {
        if (data) {
          this.$message.info('该账号已被注册')
        } else {
          return bindUsername(this.form.identifier, this.form.credential).then(() => {
            this.onGoAccount()
          })
        }
      }).finally(() => {
        this.submitting = false
      })
    })
  }

  onGoAccount () {
    this.updateType('username')
  }

  // $auth!: any
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.title {
  margin-bottom: 12px;
}

.text {
  font-size: 12px;
  margin-right: 8px;
  color: $text-secondary-color;
}

.extra {
  display: flex;
  justify-content: space-between;
}
</style>
